package com.my.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.my.dao.DAO;
import com.my.dao.impl.DAOImpl;
import com.my.entity.Role;
import com.my.entity.User;
import com.my.sec.CustomInvocationSecurityMetadataSourceService;

public class AuthFilter implements Filter {
	
	static DAO dao = new DAOImpl();
	CustomInvocationSecurityMetadataSourceService service = new CustomInvocationSecurityMetadataSourceService();
	
	// add role auth
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		
		// 登录拦截
		HttpServletRequest req = (HttpServletRequest)request;
		String url = req.getRequestURI();
		if(url.endsWith("login")) {
			chain.doFilter(request, response);
			return;
		}
		HttpSession session = req.getSession();
		User u = (User) session.getAttribute("loginUser");
		if(u == null) {
			writer.println("请登录");
			return;
		}
		
		// 权限拦截
		String hql = "from User u join fetch u.roles where u.id = ?";// 获取用户拥有的角色
		u = ((List<User>)dao.queryByHQL(hql, u.getId())).get(0);
		Set<Role> ownRoles = u.getRoles();
		String contextPath = req.getContextPath();
		url = url.substring(contextPath.length());
		List<String> needRoles = service.getAttributes(url);
		if(needRoles == null || needRoles.isEmpty()) {
			chain.doFilter(request, response);
			return;
		}
		for(String needRole: needRoles) {
			for(Role ownRole: ownRoles) {
				if(needRole.equals(ownRole.getName())) {
					chain.doFilter(request, response);
					return;
				}
			}
		}
		
		writer.println("您没有权限!!!");
	}
	
	public void destroy() {
		// TODO Auto-generated method stub
	}
	
	public static void main(String[] args) {
		String hql = "from User u join fetch u.roles where u.id = ?";
		List<User> l = dao.queryByHQL(hql, 1);
		System.out.println(l.get(0).getRoles());
		
	}

}
